package DetailedLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @projectName: JUC
 * @package: DetailedLock
 * @className: lockdemo
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/3/5 2:17
 * @version: 1.0
 */
public class lockdemo2 {
    public static void main(String[] args) {
        phone2 phone = new phone2();
        new Thread(() -> {
            phone.sms();
        }, "a").start();
        new Thread(() -> {
            phone.sms();
        }, "b").start();
    }
}

class phone2 {
    //这里就有区别 sync关键字是一个锁，这里使用lock 是两个锁，锁必须配对，否则就会死锁
    Lock lock = new ReentrantLock();

    public synchronized void sms() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "=>发短信");
            //这里也有锁
            call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public synchronized void call() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "=>打电话");
            //这里也有锁
            call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
